package com.example.jsonquynh;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainActivity extends Activity {
	static public String URL_SERVICE = "http://dongphucyduc.comyr.com/place/";
	//static public String URL_SERVICE = "http://192.168.0.133:8080/"; 
	List<Place> placeList;
	FavoriteManager favoriteManager;
	private MenuSetting menu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		placeList = new ArrayList<Place>(0);
		new Thread(new Runnable() {

			@Override
			public void run() {
				JSONObject json = new JSONParser().getJSONFromUrl(URL_SERVICE + "json/");
				try {
					JSONArray places = json.getJSONArray("place");

					for (int i = 0; i < places.length(); i++) {
						JSONObject ob = places.getJSONObject(i);
						Place place = new Place(new String(ob.getString(
								Place.JSON_ID).getBytes(), "utf-8"),
								new String(ob.getString(Place.JSON_NAME)
										.getBytes(), "utf-8"), new String(ob
										.getString(Place.JSON_ADDRESS)
										.getBytes(), "utf-8"), null, null,
								new String(ob.getJSONArray(Place.JSON_THUMB)
										.getString(0).getBytes(), "utf-8"),
								null);
						placeList.add(place);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						ListView list = (ListView) findViewById(R.id.list);

						BinderData binderData = new BinderData(
								MainActivity.this, placeList);
						list.setAdapter(binderData);
						list.setOnItemClickListener(new OnItemClickListener() {

							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {

								Intent i = new Intent();
								i.setClass(MainActivity.this, DetailPlace.class);
								i.putExtra("place", placeList.get(position));
								startActivity(i);
							}
						});
					}
				});

			}
		}).start();
		menu = new MenuSetting(this);
	}

	@Override
	protected void onResume() {
		menu.showContent();
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
